<template>
  <el-dialog
    :title="lookSee && isEdit ? '员工详情' : isEdit ? '编辑员工' : '新增员工'"
    :visible.sync="dialogVisible"
    width="80%"
    style="padding-bottom: 15vh;"
    :close-on-click-modal="false"
    :before-close="deletHandler"
  >
    <!-- :rules="formRules" -->
    <el-form ref="RefForm" :model="formData" label-width="100px" :rules="formRules" status-icon>
      <!-- 顶部 -->
      <div class="contentTop">
        <div class="divone">
          <el-form-item class="wid" label="RFID卡" prop="rfid">
            <el-input v-model="formData.rfid" :disabled="lookSee" :class="{ 'seecolor': lookSee }"></el-input>
          </el-form-item>
        </div>
        <div class="divone">
          <el-form-item class="wid" label="门禁ID" prop="accessCardID">
            <el-input v-model="formData.accessCardID" :disabled="lookSee" :class="{ 'seecolor': lookSee }"></el-input>
          </el-form-item>
        </div>
        <div class="divone">
          <el-form-item class="wid" label="人脸识别:" prop="faceDetect">
            <el-select v-model="formData.faceDetect" :disabled="lookSee" placeholder="请选择" :class="{ 'seecolor': lookSee }">
              <el-option v-for="item in faceDetectList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </div>
      </div>
      <!-- 中间部分 -->
      <div class="contentCenter">
        <div class="centerLeft">
          <div class="row">
            <div class="divone">
              <el-form-item label="员工编码" class="wid" prop="employeeCode">
                <el-input v-model="formData.employeeCode" :disabled="lookSee" class="wid" :class="{ 'seecolor': lookSee }"></el-input>
              </el-form-item>
            </div>
            <div class="divone"></div>
          </div>
          <div class="row">
            <div class="divone">
              <el-form-item label="姓名" class="wid" prop="name">
                <el-input v-model="formData.name" :disabled="lookSee" class="wid" :class="{ 'seecolor': lookSee }"></el-input>
              </el-form-item>
            </div>
            <div class="divone">
              <el-form-item label="性别" class="wid" prop="sex">
                <el-select v-model="formData.sex" :disabled="lookSee" class="wid" placeholder="请选择" :class="{ 'seecolor': lookSee }">
                  <el-option v-for="item in sexList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div class="row">
            <div class="divone">
              <el-form-item label="生日" class="wid">
                <el-date-picker v-model="formData.birthday" :disabled="lookSee" type="date" class="wid" placeholder="请选择" :class="{ 'seecolor': lookSee }"></el-date-picker>
              </el-form-item>
            </div>
            <div class="divone">
              <el-form-item label="身份证号" class="wid" prop="idCard">
                <el-input v-model="formData.idCard" :disabled="lookSee" class="wid" :class="{ 'seecolor': lookSee }"></el-input>
              </el-form-item>
            </div>
          </div>
          <div class="row">
            <div class="divone">
              <el-form-item label="电话号码" class="wid" prop="phone">
                <el-input v-model="formData.phone" :disabled="lookSee" class="wid" :class="{ 'seecolor': lookSee }"></el-input>
              </el-form-item>
            </div>
            <div class="divone">
              <el-form-item label="邮箱" class="wid">
                <el-input v-model="formData.email" :disabled="lookSee" class="wid" :class="{ 'seecolor': lookSee }"></el-input>
              </el-form-item>
            </div>
          </div>
          <div class="row">
            <div class="divone">
              <el-form-item class="wid" label="地址" prop="adress">
                <el-input v-model="formData.adress" :disabled="lookSee" class="wid" :class="{ 'seecolor': lookSee }"></el-input>
              </el-form-item>
            </div>
          </div>
          <div style="padding: 10px 0;"></div>
          <div class="row">
            <div class="divone">
              <el-form-item label="部门" class="wid" prop="departmentId">
                <el-select
                  v-model="formData.departmentId"
                  :disabled="lookSee"
                  class="wid"
                  :class="{ 'seecolor': lookSee }"
                  placeholder="请选择"
                  @change="dptChangeHandler"
                >
                  <el-option v-for="item in dptList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="divone">
              <el-form-item label="职位" class="wid" prop="jobId">
                <el-select
                  v-model="formData.jobId"
                  class="wid"
                  :class="{ 'seecolor': lookSee }"
                  :disabled="lookSee || jobDisabled"
                  :placeholder="jobPlaceholder"
                >
                  <el-option v-for="item in jobList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div class="row">
            <div class="divone">
              <el-form-item label="工种" class="wid" prop="workId">
                <el-select v-model="formData.workId" :disabled="lookSee" class="wid" :class="{ 'seecolor': lookSee }" placeholder="请选择">
                  <el-option v-for="item in workList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="divone">
              <el-form-item label="工作状态" class="wid" prop="status">
                <el-select v-model="formData.status" :disabled="lookSee" class="wid" :class="{ 'seecolor': lookSee }" placeholder="请选择">
                  <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div class="row">
            <div class="divone">
              <el-form-item class="wid" label="备注">
                <el-input v-model="formData.comment" :rows="2" :disabled="lookSee" :class="{ 'seecolor': lookSee }" class="wid" type="textarea"></el-input>
              </el-form-item>
            </div>
          </div>
        </div>
        <div class="centerRight">
          <div class="block">
            <el-image v-if="formData.photo" style="width: 150px; height: 180px;" :src="imgUrl" fit="fit"></el-image>
            <div v-else class="imgs">上传人员档案照片</div>
          </div>
          <div class="btns">
            <el-button v-if="!lookSee" size="mini" @click="addHeadPortrait">拍照</el-button>
            <el-upload
              v-if="!lookSee"
              ref="imgRef"
              class="upload-demo"
              :headers="{
                Authorization: `Bearer ${$store.getters.token}`
              }"
              :action="httpUrl"
              multiple
              :limit="1"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :show-file-list="false"
            >
              <el-button size="mini">上传</el-button>
            </el-upload>
            <el-button v-if="!lookSee" size="mini" @click="deletHttp">删除</el-button>
          </div>
        </div>
      </div>
      <!-- 底部 -->
      <!-- <div v-if="formData.faceDetect" class="contentBottom">
        <div class="title">人脸识别照片</div>
        <div class="images">
          <div class="boxLeft">
            <div class="imgList">
              <div class="imagItem">
                <el-button v-if="formData.faceDetectPhoto1" class="delBtn" type="text" @click="deleteFaceImg(1)">删除</el-button>
                <el-image v-if="formData.faceDetectPhoto1" style="width: 150px; height: 180px;" :src="imgSrc + formData.faceDetectPhoto1" fit="fit"></el-image>
                <div v-if="!formData.faceDetectPhoto1" class="noneImg">
                  <div class="imgText">上传图片</div>
                </div>
              </div>
              <div class="imagItem">
                <el-button v-if="formData.faceDetectPhoto2" class="delBtn" type="text" @click="deleteFaceImg(2)">删除</el-button>
                <el-image v-if="formData.faceDetectPhoto2" style="width: 150px; height: 180px;" :src="imgSrc + formData.faceDetectPhoto2" fit="fit"></el-image>
                <div v-if="!formData.faceDetectPhoto2" class="noneImg">
                  <div class="imgText">上传图片</div>
                </div>
              </div>
              <div class="imagItem">
                <el-button v-if="formData.faceDetectPhoto3" class="delBtn" type="text" @click="deleteFaceImg(3)">删除</el-button>
                <el-image v-if="formData.faceDetectPhoto3" style="width: 150px; height: 180px;" :src="imgSrc + formData.faceDetectPhoto3" fit="fit"></el-image>
                <div v-if="!formData.faceDetectPhoto3" class="noneImg">
                  <div class="imgText">上传图片</div>
                </div>
              </div>
            </div>
            <div>
              <el-button v-if="!lookSee" type="text" size="mini" @click="addHeadPortrait">拍照</el-button>
              <el-upload
                v-if="!lookSee"
                ref="imgRef"
                style="display: inline-block;"
                class="upload-demo"
                :headers="{
                  Authorization: `Bearer ${$store.getters.token}`
                }"
                :action="httpUrl"
                multiple
                :limit="1"
                :on-success="uploadHandler"
                :before-upload="beforeAvatarUpload"
                :show-file-list="false"
              >
                <el-button type="text" size="mini">从设备上传</el-button>
              </el-upload>
            </div>
          </div>
          <div class="boxRight"></div>
        </div>
      </div>-->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="deletHandler">取 消</el-button>
      <el-button :loading="loadingSubmit" type="primary" @click="handlerSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import dialogEditMixin from "@/mixins/dialogEdit"
  import { eleValidator } from "@/utils/tools"
  import { department, job, work, faceDetect, getMaxId, distinguish, delMaxId } from "@/api/api"
  export default {
    mixins: [dialogEditMixin],
    data() {
      return {
        maxId: null, // 员工ID
        jobDisabled: true,
        jobPlaceholder: "请选择",
        imgUrl: "",
        imgSrc: this.$imgUrl + "/",
        // 获取图片地址
        httpUrl: `${this.$imgUrl}/Common/Upload`,
        // 串口下拉框
        options: [
          {
            label: "123",
            value: 0,
          },
        ],
        // 是否启用人脸识别
        faceDetectList: [
          { label: "不启用", value: 0 },
          { label: "启用", value: 1 },
        ],
        // 性别
        sexList: [
          { label: "女", value: 0 },
          { label: "男", value: 1 },
        ],
        statusList: [
          { label: "在职", value: '1' },
          { label: "离职", value: '0' },
        ],
        // 部门
        dptList: [],
        jobList: [],
        workList: [],
        // 人脸识别照片
        fits: [
          {
            url: "",
            id: 1,
          },
          {
            url: "",
            id: 2,
          },
          {
            url: "",
            id: 3,
          },
        ],
        // 底部串口
        value: "",
        apiKey: {
          search: "/Employee/",
          add: "/Employee",
          put: "/Employee/",
        },
        // 验证规则
        formRules: {
          rfid: [
            { required: true, message: "请输入RFID卡", trigger: "blur" },
            {
              validator: eleValidator([
                { rule: "isEmpty", msg: "RFID卡不能为空" },
                { rule: 'isRepeat', msg: { value: 'RFID卡重复', url: '/Employee/Exists', key: 'rfid' } }
              ]),
              trigger: "blur",
            },
          ],
          accessCardID: [
            { required: true, message: "请输入门禁ID", trigger: "change" },
            {
              validator: eleValidator([
                { rule: "isEmpty", msg: "门禁ID不能为空" },
                { rule: 'isRepeat', msg: { value: '门禁ID重复', url: '/Employee/Exists', key: 'accessCardID' } }
              ]),
              trigger: "blur",
            },
          ],
          employeeCode: [
            { required: true, message: "请输入员工编码", trigger: "blur" },
            {
              validator: eleValidator([
                { rule: "isEmpty", msg: "员工编码不能为空" },
                { rule: 'isRepeat', msg: { value: '员工编码重复', url: '/Employee/Exists', key: 'employeeCode' } }
              ]),
              trigger: "blur",
            },
          ],
          name: [
            { required: true, message: "请输入员工姓名", trigger: "blur" },
          ],
          sex: [
            { required: true, message: "请选择", trigger: "change" },
          ],
          faceDetect: [{ required: true, message: "请选择", trigger: "change" }],
          idCard: [
            { required: true, message: "请输入身份证号", trigger: "blur" },
            {
              validator: eleValidator([{ rule: "isEmpty", msg: "身份证号不能为空" }]),
              trigger: "blur",
            },
          ],
          phone: [
            { required: true, message: "请输入手机号", trigger: "blur" },
          ],
          adress: [
            { required: true, message: "请输入地址", trigger: "blur" },
          ],
          departmentId: [{ required: true, message: "请选择", trigger: "change" }],
          jobId: [
            { required: true, message: "请选择", trigger: "change" },
          ],
          status: [{ required: true, message: "请选择", trigger: "change" }]
        },
      }
    },
    watch: {
      async searchValue(newValue, oldValue) {
        // 获取部门
        if (newValue.department) {
          this.formData.departmentId = newValue.department ? newValue.department.id : ''
          await this.dptChangeHandler(newValue.department.id)
          if (newValue.job) {
            this.formData.jobId = newValue.job ? newValue.job.id : ''
          }
        }
        // 获取工种
        if (newValue.work) {
          this.formData.workId = newValue.work ? newValue.work.id : ''
        }
        // 显示头像
        if (newValue.photo) {
          this.imgUrl = newValue.photo
        }
        if (newValue.status) {
          this.formData.status = newValue.status
        }
      },
    },
    sockets: {
      PlayerJoined: function () { },
      ReceiveMessage: function (res) {
        let obj = JSON.parse(res)
        this.formData.name = obj.Name
        this.formData.sex = obj.Gender === "男" ? 1 : 0
        this.formData.birthday = obj.Birth
        this.formData.idCard = obj.IDC
        this.formData.adress = obj.Address
      },
      TakeImage: function (res) {
        let value = res
        this.formData.photo = value[0]
        this.imgUrl = value[0]
      }
    },
    methods: {
      deletHandler() {
        try {
          delMaxId(this.maxId + 1)
        } catch (err) {
          console.log(err)
        }
        this.close()
      },
      // 提交
      handlerSubmit() {
        try {
          let obj = ''
          if (this.formData.faceDetect) {
            obj = 'open'
          } else {
            obj = 'close'
          }
          distinguish(obj, this.maxId + 1)
        } catch (err) {
          console.log(err)
        }
        this.handleSubmit()
      },
      // deleteFaceImg(value) {
      //   if (value === 1) {
      //     this.formData.faceDetectPhoto1 = ""
      //   } else if (value === 2) {
      //     this.formData.faceDetectPhoto2 = ""
      //   } else if (value === 3) {
      //     this.formData.faceDetectPhoto3 = ""
      //   }
      // },
      // 设备上传头像
      // uploadHandler(res, file) {
      //   if (res.code === 200) {
      //     if (!this.formData.faceDetectPhoto1) {
      //       this.formData.faceDetectPhoto1 = res.data.url
      //     } else if (!this.formData.faceDetectPhoto2) {
      //       this.formData.faceDetectPhoto2 = res.data.url
      //     } else if (!this.formData.faceDetectPhoto3) {
      //       this.formData.faceDetectPhoto3 = res.data.url
      //     }
      //   }
      //   // this.imgUrl = URL.createObjectURL(file.raw)
      //   this.$refs.imgRef.clearFiles()
      // },
      // 部门改变事件
      async dptChangeHandler(event) {
        let obj = { pageIndex: 1, pageSize: 1e8 }
        let result = await job("post", obj, false)
        // 职位
        this.jobList = []
        result.data.items.map((item) => {
          if (item.lenght === 0) {
            return
          } else {
            if (item.department.id === event) {
              this.jobList.push({
                label: item.jobTitle,
                value: item.id,
              })
            }
          }
        })

        this.formData.jobId = ""
        this.jobDisabled = false
      },
      // 查询部门，工种
      async getList() {
        let obj = { pageIndex: 1, pageSize: 1e8 }
        let resList = await Promise.all([
          department("post", obj, false),
          work("post", obj, false),
        ])
        // 部门
        if (resList[0].code === 200) {
          this.dptList = resList[0].data.items.map((item) => {
            if (item.lenght === 0) {
              return
            }
            return {
              label: item.deptName,
              value: item.id,
            }
          })
        }
        // 工种
        if (resList[1].code === 200) {
          this.workList = resList[1].data.items.map((item) => {
            if (item.lenght === 0) {
              return
            }
            return {
              label: item.workName,
              value: item.id,
            }
          })
        }
      },
      // 上传成功
      handleAvatarSuccess(res, file) {
        if (res.code === 200) {
          this.formData.photo = this.$imgUrl + '/' + res.data.url
        }
        this.imgUrl = URL.createObjectURL(file.raw)
        this.$refs.imgRef.clearFiles()
      },
      // 上传前
      beforeAvatarUpload(file) {
        const isJPG = file.type === "image/jpeg"
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error("上传头像图片只能是 JPG 格式!")
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!")
        }
        return isJPG && isLt2M
      },
      // 删除按钮
      deletHttp() {
        this.imgUrl = ""
        this.formData.photo = ""
        this.$refs.imgRef.clearFiles()
      },
      // 调用拍照
      async addHeadPortrait() {
        if (!this.formData.name) {
          this.$message.warning('请先输入姓名！')
          return
        }
        try {
          let response = await faceDetect('post', { name: this.formData.name })
          console.log(response)
        } catch (err) {
          console.log(err)
        }
      },
      // 请求人员ID
      async getMaxId() {
        try {
          let response = await getMaxId()
          this.maxId = response.data
        } catch (err) {
          console.log(err)
        }
      },
      resetFormData() {
        this.formData = {
          obj: {},
          employeeCode: "", // 员工编码
          name: "", // 姓名
          sex: "", // 性别
          birthday: "", // 生日
          idCard: "", // 身份证
          phone: "", // 电话号码
          email: "", // 邮箱
          adress: "", // 地址
          comment: "", // 备注
          photo: "", // 照片
          departmentId: "", // 部门
          jobId: "", // 职位
          workId: '', // 工种
          status: "", // 工作状态
          rfid: "", // rfid标签
          accessCardID: "", // 门禁ID号
          faceDetect: 1, // 面部检测
          faceDetectPhoto1: "", // 面部检测照片1
          faceDetectPhoto2: "", // 面部检测照片2
          faceDetectPhoto3: "", // 面部检测照片3
        }
      },
    },
  }
</script>

<style lang="scss" scoped>
  // 顶部
  .contentTop {
    display: flex;
    margin-right: 20px;

    .divone {
      flex: 1;
      display: flex;

      .el-select {
        width: 100%;
      }

      .el-input {
        flex: 1;
      }

      .wid {
        width: 100%;
      }
      .seecolor {
        /deep/ .el-input__inner {
          color: #999 !important;
        }
      }
    }
  }
  // 中间部分
  .contentCenter {
    display: flex;
    // 左侧信息
    .centerLeft {
      flex: 2;

      .row {
        width: 100%;
        // height: 32px;
        display: flex;

        .divone {
          flex: 1;
          display: flex;
          // align-items: center;
          // padding: 0 10px;

          .wid {
            width: 100%;
          }

          .el-input {
            flex: 1;
          }

          .seecolor {
            /deep/ .el-input__inner {
              color: #999 !important;
            }
            /deep/ .el-textarea__inner {
              color: #999 !important;
            }
          }
        }
      }
    }
    // 右侧头像
    .centerRight {
      flex: 1;
      display: flex;
      // flex-direction: row-reverse;\
      justify-content: flex-end;

      .block {
        margin-top: 36px;

        .imgs {
          width: 150px;
          height: 180px;
          line-height: 180px;
          text-align: center;
          color: #ccc;
          border: 1px solid #ccc;
        }
      }

      .btns {
        margin-right: 20px;
        margin-left: 30px;
        margin-top: 36px;

        .el-button {
          display: block;
          margin: 0;
          border: 1px solid #1e90ff;
          color: #1e90ff;
          margin-bottom: 10px;
        }
      }
    }
  }
  // 底部
  .contentBottom {
    padding: 20px;
    box-sizing: border-box;

    .title {
      position: relative;
      width: 120px;
      padding: 8px 10px;
      text-align: center;
      box-sizing: border-box;
      border: 1px solid #ccc;
      border-bottom: none;
    }

    .title::before {
      content: "";
      width: 30px;
      height: 33px;
      background-color: #fff;
      border-right: 1px solid #ccc;
      display: block;
      position: absolute;
      left: -21px;
      bottom: 0;
      transform: skewX(-30deg);
    }

    .images {
      border: 1px solid #ccc;
      padding: 20px;
      box-sizing: border-box;

      .boxLeft {
        .imgList {
          display: flex;
          margin-bottom: 10px;

          .imagItem {
            border: 1px solid #ccc;
            padding: 10px;
            margin-right: 20px;
            position: relative;
            .delBtn {
              position: absolute;
              right: 0;
              top: 0;
              padding: 0;
              margin: 0;
              z-index: 20000;
            }
          }
          // 没有上传时的盒子
          .noneImg {
            width: 150px;
            height: 180px;
            line-height: 180px;
            text-align: center;
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
            // 没有上传时的文字
            .imgText {
              color: #ccc;
              background-color: #fff;
              z-index: 10;
            }
          }
          // 斜线1
          .noneImg::before {
            content: "";
            width: 1px;
            height: 204px;
            display: block;
            background-color: #ccc;
            position: absolute;
            left: 74px;
            top: -10px;
            transform: skewX(40deg);
          }
          // 斜线2
          .noneImg::after {
            content: "";
            width: 1px;
            height: 204px;
            display: block;
            background-color: #ccc;
            position: absolute;
            left: 74px;
            top: -10px;
            transform: skewX(-40deg);
          }
        }
      }
    }
  }

  .footer {
    display: flex;

    .left {
      flex: 1;
      display: flex;
      padding: 0 20px;
      align-items: center;

      .el-select {
        margin: 0 20px;
      }
    }

    .right {
      width: 260px;
      display: flex;
    }
  }
</style>
